﻿using System;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using DbManager;
using DbManager.DataManager;
using DbManager.QueryBuilder.DataManagment;
using DbManager.QueryBuilder.DbEntity;
using DbManager.QueryBuilder.DbEntity.Bron;
using DbManager.QueryBuilder.DbEntity.Client;
using DbManager.QueryBuilder.DbEntity.Group;
using DbManager.QueryBuilder.DbEntity.IND.BazaOtdiha;
using DbManager.QueryBuilder.DbEntity.IND.Gorod;
using DbManager.QueryBuilder.DbEntity.IND.Napravlenie;
using DbManager.QueryBuilder.DbEntity.IND.Uslovia;
using DbManager.QueryBuilder.DbEntity.Komnata;
using DbManager.QueryBuilder.DbEntity.Pol;
using DbManager.QueryBuilder.DbEntity.Pot;
using DbManager.QueryBuilder.DbEntity.Price;
using DbManager.QueryBuilder.DbEntity.Viezd;

namespace TAProject.UI.Order
{
    public partial class FormTourBron : FormTemplate
    {
        private readonly Form _parentForm;
        private readonly IConnectionManager _connectionManager;
        private readonly IDataManager _dataManager;

        private readonly AEntityBron _aEntityBron;
        private readonly AEntityClient _aEntityClient;
        private readonly AEntityBazaOtdiha _aEntityBazaOtdiha;
        private readonly AEntityGorod _aEntityGorod;
        private readonly AEntityNapravlenie _aEntityNapravlenie;
        private readonly AEntityPol _aEntityPol;
        private readonly AEntityPot _aEntityPot;
        private readonly AEntityGroup _aEntityGroup;
        private readonly AEntityPrice _aEntityPrice;
        private readonly AEntityViezd _aEntityViezd;
        private readonly AEntityUslovia _aEntityUslovia;
        private readonly AEntityKomnata _aEntityKomnata;

        private readonly DataTable _dataTableMain;
        private DataTable _dataTableGroup;
        private readonly bool _isUpdate;

        private readonly bool _needClose;

        private enum ComboBoxList
        {
            ComboBoxNapravlenie,
            ComboBoxGorod,
            ComboBoxBazaOtdiha,
            ComboBoxKlass,
            ComboBoxMesta,
            ComboBoxUslovia,
            ComboBoxAll
        }

        private FormTourBron(IConnectionManager connectionManager, IDataManager dataManager, Form parentForm)
            : base(parentForm)
        {
            InitializeComponent();

            _dataManager = dataManager;
            _connectionManager = connectionManager;
            _parentForm = parentForm;

            if (_connectionManager.CheckConnection())
            {
                _dataTableMain = _dataManager.GetDataTable(GeneralQueries.GetDataTableBron(),
                                                           _connectionManager.GetConnection());
                if (_dataTableMain == null || _dataTableMain.Rows.Count < 1)
                {
                    MessageBox.Show("Ошибка получения данных из БД или необходимый набор значений отсутствует.");
                    _needClose = true;
                    FormClose();
                }
            }
            else
            {
                MessageBox.Show("Ошибка подключения к БД.");
                _needClose = true;
                FormClose();
            }
        }

        public FormTourBron(Form parentForm, IConnectionManager connectionManager, IDataManager dataManager)
            : this(connectionManager, dataManager, parentForm)
        {
            if(_needClose) return;
             _isUpdate = false;

            _aEntityClient = new EntityClient();
            _aEntityGroup = new EntityGroup();
            _aEntityPrice = new EntityPrice();
            _aEntityBazaOtdiha = new EntityBazaOtdihaByGorod();
            _aEntityNapravlenie = new EntityNapravlenie();
            _aEntityGorod = new EntityGorodByNapravlenie();
            _aEntityPol = new EntityPol();
            _aEntityPot = new EntityPot();
            _aEntityBron = new EntityBron();
            _aEntityViezd = new EntityViezd();
            _aEntityUslovia = new EntityUslovia();
            _aEntityKomnata = new EntityKomnata();

            _aEntityGroup.IDGroup = _dataManager.GetNewId(GeneralQueries.GetNewId("Бронь", "Идентификатор группы"),
                                                          _connectionManager.GetConnection());
            _aEntityPrice.ID = _dataManager.GetNewId(GeneralQueries.GetNewId("Стоимость", "Идентификатор"),
                                                     _connectionManager.GetConnection());
            _aEntityViezd.ID = _dataManager.GetNewId(GeneralQueries.GetNewId("Выезд", "Идентификатор"),
                                                     _connectionManager.GetConnection());

            if (_aEntityGroup.IDGroup == 0 || _aEntityPrice.ID == 0 || _aEntityViezd.ID == 0)
            {
                MessageBox.Show("Ошибка получения данных из БД");
                FormClose();
            }

            _parentForm.Enabled = false;

            labelViezdStatus.Text = "Не заполнено";

            FormDataTableGroup();
            ReFillComboBoxesPol(ComboBoxList.ComboBoxAll);

            comboBoxNapravlenie.SelectedValueChanged += ComboBoxNapravlenieSelectedValueChanged;
            comboBoxGorod.SelectedValueChanged += ComboBoxGorodSelectedValueChanged;
            comboBoxBazaOtdiha.SelectedValueChanged += ComboBoxBazaOtdihaSelectedValueChanged;
            comboBoxKlass.SelectedValueChanged += ComboBoxKlassSelectedValueChanged;
            comboBoxMesta.SelectedValueChanged += ComboBoxMestaSelectedValueChanged;
            comboBoxUslovia.SelectedValueChanged += ComboBoxUsloviaSelectedValueChanged;
            comboBoxPerevozshik.SelectedValueChanged += ComboBoxPerevozshikSelectedValueChanged;
        }

        public FormTourBron(Form parentForm, IConnectionManager connectionManager, IDataManager dataManager,
                            AEntityClient aEntityClient, AEntityNapravlenie aEntityNapravlenie,
                            AEntityGorod aEntityGorod, AEntityBazaOtdiha aEntityBazaOtdiha,
                            AEntityUslovia aEntityUslovia, AEntityKomnata aEntityKomnata,
                            AEntityTransport aEntityTransport, AEntityBron aEntityBron, 
                            AEntityViezd aEntityViezd, AEntityPrice aEntityPrice)
            : this(connectionManager, dataManager, parentForm)
        {
            if (_needClose) return;
            _isUpdate = true;

            _aEntityClient = aEntityClient;
            _aEntityNapravlenie = aEntityNapravlenie;
            _aEntityGorod = aEntityGorod;
            _aEntityBazaOtdiha = aEntityBazaOtdiha;
            _aEntityKomnata = aEntityKomnata;
            _aEntityUslovia = aEntityUslovia;
            _aEntityBron = aEntityBron;
            _aEntityViezd = aEntityViezd;
            _aEntityPrice = aEntityPrice;

            _aEntityGroup = new EntityGroup {IDGroup = _aEntityBron.IDGroup};
            FormDataTableGroup();
            _aEntityPol = new EntityPol {ID = _aEntityBron.IDPol};
            _aEntityPot = new EntityPot
                              {
                                  ID = _aEntityBron.IDPot,
                                  IDTransport = aEntityTransport.ID
                              };
            _aEntityPrice.ID = _aEntityBron.IDPrice;

            _parentForm.Enabled = false;

            textBoxClientName.Text = _aEntityClient.Surname + " " +
                                     _aEntityClient.Name + " " +
                                     _aEntityClient.FatherName;

            dateTimePickerDateStart.Value = _aEntityBron.DateStartOfRest;
            numericUpDownTermsLongHoliday.Value = _aEntityBron.LongOfRest;

            ReFillComboBoxesPol(ComboBoxList.ComboBoxAll);

            comboBoxNapravlenie.SelectedValueChanged += ComboBoxNapravlenieSelectedValueChanged;
            comboBoxGorod.SelectedValueChanged += ComboBoxGorodSelectedValueChanged;
            comboBoxBazaOtdiha.SelectedValueChanged += ComboBoxBazaOtdihaSelectedValueChanged;
            comboBoxKlass.SelectedValueChanged += ComboBoxKlassSelectedValueChanged;
            comboBoxMesta.SelectedValueChanged += ComboBoxMestaSelectedValueChanged;
            comboBoxUslovia.SelectedValueChanged += ComboBoxUsloviaSelectedValueChanged;
            comboBoxPerevozshik.SelectedValueChanged += ComboBoxPerevozshikSelectedValueChanged;

            if (!string.IsNullOrEmpty(_aEntityViezd.MestoSbora))
            {
                labelViezdStatus.Text = _aEntityViezd.DataSbora.ToLongDateString();
            }
            else
            {
                labelViezdStatus.Text = "Не заполнено";
            }

            checkBoxInsurance.Checked = _aEntityBron.Insurance;
            checkBoxDiscount.Checked = _aEntityBron.Discount;
        }

        #region StartOfRest-EndOfRest

        private void FormRegistration_Load(object sender, EventArgs e)
        {
            _aEntityBron.DateStartOfRest = dateTimePickerDateStart.Value;
            if (!_isUpdate) _aEntityViezd.DataSbora = _aEntityBron.DateStartOfRest;
            _aEntityBron.LongOfRest = (int) numericUpDownTermsLongHoliday.Value;
            _aEntityBron.DateEndOfRest = _aEntityBron.DateStartOfRest.AddDays(_aEntityBron.LongOfRest);
            textBoxDateEnd.Text = _aEntityBron.DateStartOfRest.AddDays(_aEntityBron.LongOfRest).ToLongDateString();
        }

        private void DateTimePickerDateStartValueChanged(object sender, EventArgs e)
        {
            _aEntityBron.DateStartOfRest = dateTimePickerDateStart.Value;
            if(!_isUpdate) _aEntityViezd.DataSbora = _aEntityBron.DateStartOfRest;
            _aEntityBron.DateEndOfRest = _aEntityBron.DateStartOfRest.AddDays(_aEntityBron.LongOfRest);
            textBoxDateEnd.Text = _aEntityBron.DateEndOfRest.ToLongDateString();
        }

        private void NumericUpDownTermsLongHolidayValueChanged(object sender, EventArgs e)
        {
            _aEntityBron.LongOfRest = (int) numericUpDownTermsLongHoliday.Value;
            _aEntityBron.DateEndOfRest = _aEntityBron.DateStartOfRest.AddDays(_aEntityBron.LongOfRest);
            textBoxDateEnd.Text = _aEntityBron.DateEndOfRest.ToLongDateString();
        }

        #endregion

        private void ButtonCancelClick(object sender, EventArgs e)
        {
            FormClose();
        }

        private void FormClose()
        {
            _parentForm.Enabled = true;
            Close();
        }

        private void ButtonClientSelectClick(object sender, EventArgs e)
        {
            var form = new FormClient(this, _dataManager, _connectionManager, _aEntityClient);
            form.ShowDialog(this);

            if (_aEntityClient.ID == 0 ||
                string.IsNullOrEmpty(_aEntityClient.Surname) ||
                string.IsNullOrEmpty(_aEntityClient.Name) ||
                string.IsNullOrEmpty(_aEntityClient.FatherName))
            {
                MessageBox.Show("Ошибка чтения данных о клиенте.");
                textBoxClientName.Text = string.Empty;
            }
            else
            {
                textBoxClientName.Text = _aEntityClient.Surname + " " +
                                         _aEntityClient.Name + " " +
                                         _aEntityClient.FatherName;
                _aEntityViezd.AdressClienta = _aEntityClient.Adress;
                CountGroupMembers();
            }
        }

        #region GroupBloсk

        private void FormDataTableGroup()
        {
            if(!_isUpdate)
            {
                _dataTableGroup = new DataTable("Группа");
                _dataTableGroup.Columns.Add("Идентификатор", typeof (int));
                _dataTableGroup.Columns.Add("Фамилия", typeof (string));
                _dataTableGroup.Columns.Add("Имя", typeof (string));
                _dataTableGroup.Columns.Add("Отчество", typeof (string));
                _dataTableGroup.Columns.Add("Ребенок", typeof (bool));
            }
            else
            {
                AEntityGroup aEntityGroupSingle = new EntityGroupSingle { IDGroup = _aEntityGroup.IDGroup };
                var dataTable = _dataManager.GetDataTable(aEntityGroupSingle.GetSelectQuery(),
                                                          _connectionManager.GetConnection());
                if (dataTable != null)
                {
                    _dataTableGroup = dataTable;
                    CountGroupMembers();
                }
                else
                {
                    MessageBox.Show("Ошибка получения данных о группе.");
                    FormClose();
                }
            }

            dataGridViewGroup.DataSource = _dataTableGroup;
            dataGridViewGroup.Columns["Идентификатор"].Visible = false;
        }

        private void ButtonGroupAddClick(object sender, EventArgs e)
        {
            if (_aEntityGroup.IDGroup == 0) return;
            if (!string.IsNullOrEmpty(_aEntityClient.Surname))
            {
                var form = new FormGroupAdd(this, _aEntityClient.Surname);
                form.ShowDialog(this);

                if (!form.Complete) return; //была нажата кнопка отмена

                var newRow = _dataTableGroup.NewRow();
                newRow["Фамилия"] = form.Surname;
                newRow["Имя"] = form.GName;
                newRow["Отчество"] = form.FName;
                newRow["Ребенок"] = form.IsChild;
                _dataTableGroup.Rows.Add(newRow);
                CountGroupMembers();
            }
            else
            {
                MessageBox.Show("Сначала заполните поле \"ФИО заказчика\".");
            }
        }

        private void ButtonGroupEditClick(object sender, EventArgs e)
        {
            if (dataGridViewGroup.CurrentRow != null && dataGridViewGroup.CurrentRow.Index > -1)
            {
                var currentRow = dataGridViewGroup.CurrentRow.Index;
                var form = new FormGroupAdd(this,
                    _dataTableGroup.Rows[currentRow]["Фамилия"].ToString(),
                    _dataTableGroup.Rows[currentRow]["Имя"].ToString(),
                    _dataTableGroup.Rows[currentRow]["Отчество"].ToString(),
                    (bool) _dataTableGroup.Rows[currentRow]["Ребенок"]);
                form.ShowDialog(this);

                if (!form.Complete) return;
                _dataTableMain.Rows[currentRow].BeginEdit();
                _dataTableGroup.Rows[currentRow]["Фамилия"] = form.Surname;
                _dataTableGroup.Rows[currentRow]["Имя"] = form.GName;
                _dataTableGroup.Rows[currentRow]["Отчество"] = form.FName;
                _dataTableGroup.Rows[currentRow]["Ребенок"] = form.IsChild;
                _dataTableGroup.Rows[currentRow].EndEdit();
                CountGroupMembers();
            }
        }

        private void ButtonGroupDeleteClick(object sender, EventArgs e)
        {
            if (dataGridViewGroup.CurrentRow != null && dataGridViewGroup.CurrentRow.Index > -1)
            {
                _dataTableGroup.Rows[dataGridViewGroup.CurrentRow.Index].Delete();
                CountGroupMembers();
            }
        }

        private void CountGroupMembers()
        {
            var counter = _dataTableGroup.Rows.Cast<DataRow>().Count(row => row.RowState != DataRowState.Deleted);
            if (counter == 0)
            {
                labelChildren.Text = (0).ToString();
                labelAdults.Text = (1).ToString();
                labelAll.Text = (int.Parse(labelChildren.Text) + int.Parse(labelAdults.Text)).ToString();
                return;
            }
            labelChildren.Text = _dataTableGroup.AsEnumerable().Where(row => row.RowState != DataRowState.Deleted 
                                                                             && row.Field<bool>("Ребенок")).Count().ToString();
            labelAdults.Text = (_dataTableGroup.AsEnumerable().Where(row => row.RowState != DataRowState.Deleted
                                                                           && !row.Field<bool>("Ребенок")).Count()+1).ToString();
            labelAll.Text = (int.Parse(labelChildren.Text) + int.Parse(labelAdults.Text)).ToString();
        }

        #endregion

        private void CheckBoxInsuranceCheckStateChanged(object sender, EventArgs e)
        {
            _aEntityBron.Insurance = checkBoxInsurance.Checked;
        }

        private void CheckBoxDiscountCheckStateChanged(object sender, EventArgs e)
        {
            _aEntityBron.Discount = checkBoxDiscount.Checked;
        }

        private void ButtonViezdEditClick(object sender, EventArgs e)
        {
            var form = new FormTourViezd(this, _aEntityViezd);
            form.ShowDialog(this);
            labelViezdStatus.Text = !string.IsNullOrEmpty(_aEntityViezd.MestoSbora) 
                ? _aEntityViezd.DataSbora.ToLongDateString() 
                : "Не заполнено";
        }

        private void FormRegistrationTour_FormClosing(object sender, FormClosingEventArgs e)
        {
            //это если эту форму закрывает дочернее окно
            if (_parentForm.Enabled == false)
            {
                _parentForm.Enabled = true;
            }
        }

        private void ReFillComboBoxesPol(ComboBoxList startPoint)
        {
            switch (startPoint)
            {
                case ComboBoxList.ComboBoxNapravlenie:
                    if (startPoint != ComboBoxList.ComboBoxNapravlenie)
                    {
                        FillComboBoxFromDataTable(comboBoxNapravlenie, _dataTableMain, "NapravlenieID",
                                                  "NapravlenieName");
                    }
                    if (_aEntityNapravlenie.ID == 0)
                    {
                        _aEntityNapravlenie.ID = (int) comboBoxNapravlenie.SelectedValue;
                    }
                    else
                    {
                        comboBoxNapravlenie.SelectedValue = _aEntityNapravlenie.ID;
                    }
                    goto case ComboBoxList.ComboBoxGorod;
                case ComboBoxList.ComboBoxGorod:
                    if (_aEntityNapravlenie.ID == 0)
                    {
                        MessageBox.Show("Ошибка получения данных о направлении.");
                    }
                    else
                    {
                        _aEntityGorod.IDNapravlenie = _aEntityNapravlenie.ID;
                        if (startPoint != ComboBoxList.ComboBoxGorod)
                        {
                            var gorodFilteredByNapravlenie = _dataTableMain.AsEnumerable().
                                Where(row => row.Field<int>("NapravlenieID") == _aEntityNapravlenie.ID).CopyToDataTable();
                            FillComboBoxFromDataTable(comboBoxGorod, gorodFilteredByNapravlenie, "GorodID", "GorodName");
                        }
                        if (_aEntityGorod.ID == 0)
                        {
                            _aEntityGorod.ID = (int) comboBoxGorod.SelectedValue;
                        }
                        else
                        {
                            comboBoxGorod.SelectedValue = _aEntityGorod.ID;
                        }

                        var perevozshFilteredByGorod = _dataTableMain.AsEnumerable().
                            Where(row => row.Field<int>("GorodID") == _aEntityGorod.ID).CopyToDataTable();
                        FillComboBoxFromDataTable(comboBoxPerevozshik, perevozshFilteredByGorod, "TransportID",
                                                  "TransportPerevozshik");
                        goto case ComboBoxList.ComboBoxBazaOtdiha;
                    }
                    break;
                case ComboBoxList.ComboBoxBazaOtdiha:
                    if (_aEntityGorod.ID == 0)
                    {
                        MessageBox.Show("Ошибка получения данных о городе.");
                    }
                    else
                    {
                        _aEntityBazaOtdiha.IDGorod = _aEntityGorod.ID;
                        if (startPoint != ComboBoxList.ComboBoxBazaOtdiha)
                        {
                            var bazaOtdihaFilteredByForod = _dataTableMain.AsEnumerable().
                                Where(row => row.Field<int>("GorodID") == _aEntityGorod.ID).CopyToDataTable();
                            FillComboBoxFromDataTable(comboBoxBazaOtdiha, bazaOtdihaFilteredByForod, "BazaOtdihaID",
                                                      "BazaOtdihaName");
                        }
                        if (_aEntityBazaOtdiha.ID == 0)
                        {
                            _aEntityBazaOtdiha.ID = (int) comboBoxBazaOtdiha.SelectedValue;
                        }
                        else
                        {
                            comboBoxBazaOtdiha.SelectedValue = _aEntityBazaOtdiha.ID;
                        }
                        ComboBoxPerevozshikSelectedValueChanged(null, null);
                        goto case ComboBoxList.ComboBoxKlass;
                    }
                    break;
                case ComboBoxList.ComboBoxKlass:
                    if (_aEntityBazaOtdiha.ID == 0)
                    {
                        MessageBox.Show("Ошибка получения данных о базе отдыха.");
                    }
                    else
                    {
                        if (startPoint != ComboBoxList.ComboBoxKlass)
                        {
                            var klassFilteredByBazaOtdiha = _dataTableMain.AsEnumerable().
                                Where(row => row.Field<int>("BazaOtdihaID") == _aEntityBazaOtdiha.ID).CopyToDataTable();
                            FillComboBoxFromDataTable(comboBoxKlass, klassFilteredByBazaOtdiha, "KomnataKlass",
                                                      "KomnataKlass");
                        }
                        if (_aEntityKomnata.ID == 0)
                        {
                            _aEntityKomnata.Klass = comboBoxKlass.SelectedValue.ToString();
                        }
                        else
                        {
                            comboBoxKlass.SelectedValue = _aEntityKomnata.Klass;
                        }
                        goto case ComboBoxList.ComboBoxMesta;
                    }
                    break;
                case ComboBoxList.ComboBoxMesta:
                    if (_aEntityBazaOtdiha.ID == 0 || string.IsNullOrEmpty(_aEntityKomnata.Klass))
                    {
                        MessageBox.Show("Ошибка получения данных о классе комнаты.");
                    }
                    else
                    {
                        if (startPoint != ComboBoxList.ComboBoxMesta)
                        {
                            var mestaFilteredByBoAndKlass = _dataTableMain.AsEnumerable().
                                Where(row => row.Field<int>("BazaOtdihaID") == _aEntityBazaOtdiha.ID).
                                Where(row => row.Field<string>("KomnataKlass") == _aEntityKomnata.Klass).
                                CopyToDataTable();
                            FillComboBoxFromDataTable(comboBoxMesta, mestaFilteredByBoAndKlass, "KomnataID",
                                                      "KomnataMesta");
                        }
                        if (_aEntityKomnata.ID == 0)
                        {
                            _aEntityKomnata.ID = (int) comboBoxMesta.SelectedValue;
                        }
                        else
                        {
                            comboBoxMesta.SelectedValue = _aEntityKomnata.ID;
                        }
                        goto case ComboBoxList.ComboBoxUslovia;
                    }
                    break;
                case ComboBoxList.ComboBoxUslovia:
                    if (_aEntityBazaOtdiha.ID == 0 || _aEntityKomnata.ID == 0)
                    {
                        MessageBox.Show("Ошибка получения данных о количестве мест.");
                    }
                    else
                    {
                        if (startPoint != ComboBoxList.ComboBoxUslovia)
                        {
                            var usloviaFilteredByBoAndKomnata = _dataTableMain.AsEnumerable().
                                Where(row => row.Field<int>("BazaOtdihaID") == _aEntityBazaOtdiha.ID).
                                Where(row => row.Field<int>("KomnataID") == _aEntityKomnata.ID).
                                CopyToDataTable();
                            FillComboBoxFromDataTable(comboBoxUslovia, usloviaFilteredByBoAndKomnata, "UsloviaID",
                                                      "UsloviaName");
                        }
                        if (_aEntityUslovia.ID == 0)
                        {
                            _aEntityUslovia.ID = (int) comboBoxUslovia.SelectedValue;
                        }
                        else
                        {
                            comboBoxUslovia.SelectedValue = _aEntityUslovia.ID;
                        }
                        //получаем цену проживания
                        if (_aEntityBazaOtdiha.ID == 0 ||
                            _aEntityKomnata.ID == 0 ||
                            _aEntityUslovia.ID == 0)
                        {
                            MessageBox.Show("Извлечены не все данные для получения цены.");
                        }
                        else
                        {
                            var potFilteredbyBoAndKomnataAndUslovia = _dataTableMain.AsEnumerable().
                                Where(row => row.Field<int>("BazaOtdihaID") == _aEntityBazaOtdiha.ID).
                                Where(row => row.Field<int>("KomnataID") == _aEntityKomnata.ID).
                                Where(row => row.Field<int>("UsloviaID") == _aEntityUslovia.ID).
                                CopyToDataTable();
                            _aEntityPol.ID = (int) potFilteredbyBoAndKomnataAndUslovia.Rows[0]["PolID"];
                            _aEntityPol.Price = (decimal) potFilteredbyBoAndKomnataAndUslovia.Rows[0]["PolPrice"];
                            _aEntityPol.IDBazaOtdiha = _aEntityBazaOtdiha.ID;
                            _aEntityPol.IDKomnata = _aEntityKomnata.ID;
                            _aEntityPol.IDUslovia = _aEntityUslovia.ID;

                            textBoxCenaProjivania.Text = _aEntityPol.Price.ToString();
                        }
                    }
                    break;
                case ComboBoxList.ComboBoxAll:
                    goto case ComboBoxList.ComboBoxNapravlenie;
            }
        }

        private static void FillComboBoxFromDataTable(ListControl comboBox, DataTable dataTable, string valueMember,
                                                      string displayMember)
        {
            comboBox.DataSource = dataTable.AsEnumerable().
                Distinct(new DataTableComparer(displayMember)).
                CopyToDataTable().DefaultView;
            comboBox.ValueMember = valueMember;
            comboBox.DisplayMember = displayMember;
        }

        #region ComboBox Events

        private void ComboBoxNapravlenieSelectedValueChanged(object sender, EventArgs e)
        {
            ResetAllValues(ComboBoxList.ComboBoxNapravlenie);
            _aEntityNapravlenie.ID = (int) comboBoxNapravlenie.SelectedValue;
            ReFillComboBoxesPol(ComboBoxList.ComboBoxNapravlenie);
        }

        private void ComboBoxGorodSelectedValueChanged(object sender, EventArgs e)
        {
            ResetAllValues(ComboBoxList.ComboBoxGorod);
            _aEntityGorod.ID = (int) comboBoxGorod.SelectedValue;
            ReFillComboBoxesPol(ComboBoxList.ComboBoxGorod);
        }

        private void ComboBoxBazaOtdihaSelectedValueChanged(object sender, EventArgs e)
        {
            ResetAllValues(ComboBoxList.ComboBoxBazaOtdiha);
            _aEntityBazaOtdiha.ID = (int) comboBoxBazaOtdiha.SelectedValue;
            ReFillComboBoxesPol(ComboBoxList.ComboBoxBazaOtdiha);
        }

        private void ComboBoxKlassSelectedValueChanged(object sender, EventArgs e)
        {
            ResetAllValues(ComboBoxList.ComboBoxKlass);
            _aEntityKomnata.Klass = comboBoxNapravlenie.SelectedValue.ToString();
            ReFillComboBoxesPol(ComboBoxList.ComboBoxKlass);
        }

        private void ComboBoxMestaSelectedValueChanged(object sender, EventArgs e)
        {
            ResetAllValues(ComboBoxList.ComboBoxMesta);
            _aEntityKomnata.ID = (int) comboBoxMesta.SelectedValue;
            ReFillComboBoxesPol(ComboBoxList.ComboBoxMesta);
        }

        private void ComboBoxUsloviaSelectedValueChanged(object sender, EventArgs e)
        {
            ResetAllValues(ComboBoxList.ComboBoxUslovia);
            _aEntityUslovia.ID = (int) comboBoxUslovia.SelectedValue;
            ReFillComboBoxesPol(ComboBoxList.ComboBoxUslovia);
        }

        private void ComboBoxPerevozshikSelectedValueChanged(object sender, EventArgs e)
        {
            /*_aEntityPot.IDTransport = (int) comboBoxPerevozshik.SelectedValue;
            var aEntityPotByGorodAndPerev = new EntityPotByGorodAndPerev
                                                {
                                                    IDGorod = _aEntityGorod.ID,
                                                    Default = _aEntityPot.IDTransport.ToString()
                                                };
            var dataTable = _dataManager.GetDataTable(aEntityPotByGorodAndPerev.GetSelectQuery(),
                                                      _connectionManager.GetConnection());*/
            _aEntityPot.IDTransport = (int) comboBoxPerevozshik.SelectedValue;
            var potByGorodAndTransport = _dataTableMain.AsEnumerable().
                Where(row => row.Field<int>("GorodID") == _aEntityGorod.ID).
                Where(row => row.Field<int>("TransportID") == _aEntityPot.IDTransport).
                CopyToDataTable();

            textBoxTransport.Text = potByGorodAndTransport.Rows[0]["TransportCar"].ToString();
            textBoxCenaProezdaA.Text = potByGorodAndTransport.Rows[0]["PotAdult"].ToString();
            textBoxCenaProezdaC.Text = potByGorodAndTransport.Rows[0]["PotChild"].ToString();
            _aEntityPot.ID = (int) potByGorodAndTransport.Rows[0]["PotID"];
        }

        #endregion

        private void ResetAllValues(ComboBoxList startPosition)
        {
            switch (startPosition)
            {
                case ComboBoxList.ComboBoxNapravlenie:
                    _aEntityNapravlenie.ID = 0;
                    goto case ComboBoxList.ComboBoxGorod;
                case ComboBoxList.ComboBoxGorod:
                    _aEntityGorod.ID = 0;
                    goto case ComboBoxList.ComboBoxBazaOtdiha;
                case ComboBoxList.ComboBoxBazaOtdiha:
                    _aEntityBazaOtdiha.ID = 0;
                    goto case ComboBoxList.ComboBoxKlass;
                case ComboBoxList.ComboBoxKlass:
                    _aEntityKomnata.Klass = string.Empty;
                    goto case ComboBoxList.ComboBoxMesta;
                case ComboBoxList.ComboBoxMesta:
                    _aEntityKomnata.ID = 0;
                    goto case ComboBoxList.ComboBoxUslovia;
                case ComboBoxList.ComboBoxUslovia:
                    _aEntityUslovia.ID = 0;
                    break;
            }
        }

        private void ButtonSubmitClick(object sender, EventArgs e)
        {
            if (DataFillChecker())
            {
                _aEntityBron.IDClient = _aEntityClient.ID;
                _aEntityBron.IDGroup = _aEntityGroup.IDGroup;
                _aEntityBron.IDPol = _aEntityPol.ID;
                _aEntityBron.IDPot = _aEntityPot.ID;
                _aEntityBron.IDPrice = _aEntityPrice.ID;
                _aEntityBron.IDViezd = _aEntityViezd.ID;

                var form = new FormTourPrice(_parentForm, this, _aEntityBron, _dataManager, _connectionManager, _aEntityViezd,
                                             _aEntityPrice, _dataTableGroup, _isUpdate);
                form.ShowDialog(this);
            }
            else
            {
                MessageBox.Show("Не все поля заполнены.");
            }
        }

        private bool DataFillChecker()
        {
            if (_aEntityClient.ID == 0 ||
                _aEntityGroup.IDGroup == 0 ||
                _aEntityPol.ID == 0 ||
                _aEntityPot.ID == 0 ||
                _aEntityPrice.ID == 0 ||
                _aEntityViezd.ID == 0)
            {
                return false;
            }
            return true;
        }
    }
}